package org.springframework.data.jdbc.repository.config;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.relational.core.dialect.Dialect;
import org.springframework.data.relational.core.dialect.SQLiteDialect;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.lang.Nullable;

public class SqliteDialectProvider implements DialectResolver.JdbcDialectProvider {
	
	private static final Log LOG = LogFactory.getLog(SqliteDialectProvider.class);
	
	@Override
	public Optional<Dialect> getDialect(JdbcOperations operations) {
		return Optional.ofNullable(operations.execute((ConnectionCallback<Dialect>) SqliteDialectProvider::getDialect));
	}
	
	@Nullable
	private static Dialect getDialect(Connection connection) throws SQLException  {
		
		DatabaseMetaData metaData = connection.getMetaData();

		String name = metaData.getDatabaseProductName().toLowerCase(Locale.ENGLISH);
		
		if (name.contains("sqlite")) {
			return SQLiteDialect.INSTANCE;
		}
		
		LOG.info(String.format("Couldn't determine Dialect for \"%s\"", name));
		return null;
	}
}
